new Vue({
    el: '#app',
    data: {
        product: {
            id: '',
            name: '',
            image: '',
            price: 0,
            description: '',
            specs: [],
        },
        comments: [

        ],
        quantity: 1,
        showSuccessModal: false,
        successModalTimer: null,
        filterType: 'all',
        // 商品规格数据
        productSpecs: [],
        // 已选择的规格 {specId: attributeId}
        selectedSpecs: {},
    },
    computed: {
        averageRating() {
            if (this.comments.length === 0) return 0;
            const total = this.comments.reduce((sum, comment) => sum + comment.grade, 0);
            return total / this.comments.length;
        },
        goodReviewsCount() {
            return this.comments.filter(c => c.grade >= 4).length;
        },
        fetchGoodReviewsCount() {
            //获取商品好评
            this.comments = this.comments.filter(c => c.grade >= 4);
        },
        mediumReviewsCount() {
            return this.comments.filter(c => c.grade === 3).length;
        },
        badReviewsCount() {
            return this.comments.filter(c => c.grade <= 2).length;
        },
        withImageReviewsCount() {
            return this.comments.filter(c => c.images && c.images.length > 0).length;
        },
        filteredComments() {
            switch (this.filterType) {
                case 'good':
                    return this.comments.filter(c => c.grade >= 4);
                case 'medium':
                    return this.comments.filter(c => c.grade === 3);
                case 'bad':
                    return this.comments.filter(c => c.grade <= 2);
                case 'withImage':
                    return this.comments.filter(c => c.images && c.images.length > 0);
                default:
                    return this.comments;
            }
        }
    },
    methods: {
        getInitials(name) {
            if (!name) return '';
            const names = name.split(' ');
            let initials = names[0].substring(0, 1);
            if (names.length > 1) {
                initials += names[names.length - 1].substring(0, 1);
            }
            return initials;
        },
        getProductIdFromUrl() {
            const params = new URLSearchParams(window.location.search);
            return params.get('commodityId');
        },
        fetchProduct() {
            const id = this.getProductIdFromUrl();
            if (!id) return;
            // 获取商品详情
            $.ajax({
                url: 'http://localhost:8080/commodity/findCommodityById',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: { id: id },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        this.product = res.data;
                        this.product.image = 'http://localhost:8080' + res.data.commodityPicture[0].commodityImageUrl
                    } else {
                        alert('商品信息加载失败');
                    }
                },
                error: () => {
                    alert('商品信息加载失败');
                }
            });
        },
        // 获取评论
        fetchComments() {
            $.ajax({
                url: "http://localhost:8080/comment/listComment",
                type: "get",
                data: {
                    productId: this.getProductIdFromUrl()
                },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    this.comments = res.data;
                    this.comments.map(item => {
                        if (item.isAnonymous == 1) {
                            item.user.userName = '匿名用户';
                        }
                        item.user.avatar = "http://localhost:8080" + item.user.avatar
                        item.commentImages.map(item => {
                            item.imageUrl = "http://localhost:8080" + item.imageUrl
                        })
                    })
                    // console.log(this.comments[0].user.avatar);

                }
            })
        },
        // 数量减
        decreaseQuantity() {
            if (this.quantity > 1) this.quantity--;
        },
        // 数量加
        increaseQuantity() {
            this.quantity++;
        },
        addToCart() {
            // 加入购物车逻辑
            $.ajax({
                url: 'http://localhost:8080/cart/addCommodityToCart',
                type: 'POST',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    userId: localStorage.getItem('userId'),
                    productId: this.product.commodityId,
                    quantity: this.quantity,
                    selectedSpecs: this.getSelectedSpecsArray() // 添加规格信息
                },
                traditional:true,
                success: (res) => {
                    if (res.code === 200) {
                        this.showSuccessModal = true;
                        if (this.successModalTimer) {
                            clearTimeout(this.successModalTimer);
                        }
                        // 3秒后弹窗自动关闭
                        this.successModalTimer = setTimeout(() => {
                            this.showSuccessModal = false;
                        }, 3000);
                    } else {
                        console.log('加入购物车失败：' + res.message);
                    }
                },
                error: () => {
                    alert('加入购物车失败');
                }
            });
        },
        // 点击立即购买
        buyNow() {
            // 准备购买的商品信息，发送包含商品ID和数量的单个对象
            const commodityId = this.product.commodityId;
            console.log(commodityId);

            // 创建一个对象来存储商品ID、数量和规格信息
            const dataToSend = {};
            dataToSend[this.product.commodityId] = {
                quantity: this.quantity,
                selectedSpecs: this.getSelectedSpecsArray()
            };

            // 将对象转换为 JSON 字符串
            const dataToSendJSON = JSON.stringify(dataToSend);

            // 发送AJAX请求到后台，准备订单并获取订单标识符
            $.ajax({
                url: 'http://localhost:8080/cart/buyCommodity?userId=' + localStorage.getItem('userId'),
                type: 'POST',
                contentType: 'application/json',
                data: dataToSendJSON,
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        // 订单准备成功，跳转到订单确认页
                        window.location.href = `order-confirm-test.html?orderId=${res.data}`;
                    } else {
                        alert('直接购买失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，直接购买失败。');
                    console.error(status, error);
                }
            });
        },
        // 点击去购物车直接跳转到购物车
        goToCart() {
            if (this.successModalTimer) {
                clearTimeout(this.successModalTimer);
            }
            this.showSuccessModal = false;
            window.location.href = 'cart.html';
        },
        fetchProductSpecs() {
            const id = this.getProductIdFromUrl();
            if (!id) return;

            // 获取商品规格数据
            $.ajax({
                url: 'http://localhost:8080/productSpec/getProductSpec',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: { productId: id },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        this.productSpecs = res.data;
                        // 初始化选择第一个属性
                        this.productSpecs.forEach(spec => {
                            if (spec.attributes && spec.attributes.length > 0) {
                                this.$set(this.selectedSpecs, spec.specId, spec.attributes[0].attributeId);
                            }
                        });
                    } else {
                        console.log('商品规格加载失败：' + res.message);
                    }
                },
                error: () => {
                    console.log('商品规格加载失败');
                }
            });
        },
        // 选择规格
        selectSpec(specId, attributeId) {
            // this.selectedSpecs[specId] = attributeId;
            this.$set(this.selectedSpecs, specId, attributeId);
        },
        // 获取规格名称
        getSpecName(specId) {
            const spec = this.productSpecs.find(s => s.specId === specId);
            return spec ? spec.specName : '';
        },
        // 获取属性值
        getAttributeValue(attributeId) {
            for (let spec of this.productSpecs) {
                const attr = spec.attributes.find(a => a.attributeId === attributeId);
                if (attr) return attr.attributeValue;
            }
            return '';
        },
        // // 获取已选择的规格字符串
        // getSelectedSpecsString() {
        //     const specs = [];
        //     for (let specId in this.selectedSpecs) {
        //         const specName = this.getSpecName(specId);
        //         const attrValue = this.getAttributeValue(this.selectedSpecs[specId]);
        //         specs.push(`${specName}:${attrValue}`);
        //     }
        //     console.log(specs);
        //     return specs.join(', ');
        // },
        // 获取已选择的规格数组
        getSelectedSpecsArray() {
            const specs = [];
            for (let specId in this.selectedSpecs) {
                const specName = this.getSpecName(specId);
                const attrValue = this.getAttributeValue(this.selectedSpecs[specId]);
                specs.push(`${specName}:${attrValue}`);
            }
            console.log(specs);
            return specs;
        },
    },
    created() {
        this.fetchProduct();
        this.fetchComments();
        this.fetchProductSpecs();
    }
});